package kr.go.nih.biomedi.pSEVA.bean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

public class RuntimeThread {
	private String cmd;
	private Process p = null;
	private Boolean result = false;

	public String getCmd() {
		return cmd;
	}

	public void setCmd(String cmd) {
		this.cmd = cmd;
	}

	public String execute() {
		String strCmd = this.getCmd();

		try {
			String[] CmdArray = strCmd.split(",");
			p = new ProcessBuilder(CmdArray).start();

			StreamPrintThread errprint = new StreamPrintThread(p.getErrorStream());
			StreamPrintThread okprint = new StreamPrintThread(p.getInputStream());

			p.getOutputStream().close();

			errprint.start();
			okprint.start();

			int rst = p.waitFor();

			if (0 == rst) {
				System.out.println("RunProgram success : " + strCmd);
				result = true;
			} else {
				System.out.println("RunProgram fail (rst:" + rst + ") : "
						+ strCmd);
				result = false;
			}

		} catch (InterruptedException ie) {
			ie.printStackTrace();
			result = false;
		} catch (IOException ioe) {
			ioe.printStackTrace();
			// result = false;
		} finally {
			if (null != p) {
				p.destroy();
			}
		}

		if (result == true) {
			return "true";
		} else {
			return "false";
		}
	}

	public String getResult() {
		if (result == true) {
			return "true";
		} else {
			return "false";
		}
	}

	class StreamPrintThread extends Thread {
		private BufferedReader br = null;

		public StreamPrintThread(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		public void close() {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try {
				String line = "";
				while ((line = br.readLine()) != null) {
					System.out.println(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				close();
			}
		}
	}
}
